import cv2
import time
import os
from flask import request
from hyperlpr import HyperLPR_PlateRecogntion
from util import allowed_file, save_photo, make_api_response


def recognize():
    """
    获取保存图片并识别图片
    :return: 图片完整路径
    """
    # 获取图片
    photo = request.files.get('photo')
    if photo and allowed_file(photo.filename):
        file_full_path = save_photo(photo)
        img_name = photo.filename.rsplit('.', 1)[0]
        return recognize_photo(file_full_path, img_name)


def recognize_photo(file_full_path: str, img_name: str):
    """
    传入图片的路径进行识别
    :return: dict aip
    """
    # 识别车牌号码
    start = time.time()
    image = cv2.imread(file_full_path)
    result_list = HyperLPR_PlateRecogntion(image)
    use_time = "{:.2f}S".format(time.time() - start)
    img_size = "{}KB".format(os.path.getsize(file_full_path) / 1024)

    # 识别成功
    if result_list and len(result_list) == 1:
        if result_list[0] and len(result_list[0]) == 3:
            plate = result_list[0][0]
            confidence = result_list[0][1]
            location = result_list[0][2]

            return make_api_response(status=0,
                                     msg='识别成功',
                                     plate=plate,
                                     confidence=float(confidence),
                                     location=location,
                                     use_time=use_time,
                                     img_size=img_size,
                                     result_photo=file_full_path,
                                     img_name=img_name)
    else:
        return make_api_response(1, '识别失败')
